local extension = Package:new("MahjongSoul_ty_1v2", Package.SpecialPack)
extension.extensionName = "MahjongSoul"
local ty_desc_1v2 = [[
  # 兵临城下模式简介

  ___

  游戏由三人进行，通过倍率抢地主，倍率高者扮演城主（主公），其他两人扮演联军（反贼），基础将框为6个，城主额外+2选将。

  移除乐不思蜀和兵粮寸断，新增专属卡牌，请移步拓展包管理开启【兵临城下卡牌】后游玩。

  联军获得以下额外技能：

  - **歃血**：锁定技，每局游戏限三次，防止你对友军造成伤害(第三回合失去此效果)。

  城主选将框+2，增加1点体力上限和体力，根据城池，获得以下额外技能：

  - **襄阳**：结束阶段开始时，摸一张牌，然后执行一个额外的出牌或摸牌阶段。

  - **樊城**：限定技，出牌阶段，你可以令你本局游戏【杀】或非【杀】造成的伤害+1。

  - **江陵**：出牌阶段开始时，你选择普通锦囊牌和基本牌于本回合使用时：1.额外指定一个目标且额外目标无法响应此牌，2.无次数和距离限制。

  - **虎牢**：锁定技，你视为拥有〖无双〗/〖马术〗，且不能成为延迟锦囊牌的目标，摸牌阶段额定摸牌数+1。

  - **徐州**：你的初始手牌和手牌上限+3；结束阶段，你可以重铸至多两张牌。

  - **合肥**：摸牌阶段，你可以获得一名其他角色的一张手牌；出牌阶段使用【杀】的次数+1。

  - **颍川**：当有角色的判定牌生效后，你摸一张牌；你于回合内首次使用一种类型的牌时，你可以进行一次判定，若为红桃，你可以对自己造成一点伤害。

  - **洛阳**：锁定技，每轮开始时，你选择对一名联军造成0~2点伤害，若伤害值为0，你摸两张牌，于本轮结束时可再次发动该技能，并将伤害值改为1。

  - **陈仓**：弃牌阶段结束时，你可以弃置任意角色区域内至多共计X张牌(X为5-你的手牌数，至少为1)。

  - **荆州**：你可以回复一点体力，将所有手牌当做一张【白衣渡江】使用。

  - **永安**：锁定技，你始终跳过摸牌和弃牌阶段，出牌阶段开始和结束时，若你的体力值不为1，失去一点体力，摸两张牌；当有角色失去体力后，你摸一张牌。

  - **葭萌**：出牌阶段限一次，你可以交给一名联军一张牌，其有20％概率令一名联军死亡，否则你视为对其使用一张【杀】。

  - **宛城**：限定技，出牌阶段结束时，你可以对一名角色使用所有伤害牌，此技能结算后若其没有死亡，你废除所有装备栏。

  - **许昌**：锁定技，体力值小于你的其他角色非锁定技失效，结束阶段，你有50％受到一点雷电伤害。

  - **寿春**：结束阶段，你可以选择一项，不能与上次选择的选项相同：1.回复点体力；2.将手牌调整至X(X为存活角色数，至少为你的体力值)。

  当联军被击杀后，另一名联军可以选择：摸两张牌，或者回复1点体力。

  第六轮起，联军获得兵尽(结束阶段失去一点体力)，城主获得粮绝(摸牌阶段少摸一张牌)。

  游戏第八轮结束时，若城主存活，城主获胜。

  击杀联军的人没有摸三张牌的奖励。

  其余胜利规则与身份局一致。
]]
local witheextensionName = { "MahjongSoul", "moepack", "tenyear", "ol", "jsrg", "mobile", "mougong", "overseas", "shzl",
"thbattle",
    "sp", "yj" }
Fk:addMiniGame {
    name = "ty_1v2_selectdizhu",
    qml_path = "packages/MahjongSoul/qml/ChooseGeneralFor1v2",
    default_choice = function(player, data)
        return 1
    end,
    update_func = function(player, data)
        local room = player.room
        for i, p in ipairs(room.players) do
            p:doNotify("UpdateMiniGame", data)
        end
    end,
}

Fk:addMiniGame {
    name = "ty_1v2_sel",
    qml_path = "packages/MahjongSoul/qml/2v2",
    default_choice = function(player, data)
        return table.random(data.me, 1)
    end,
    update_func = function(player, data)
        local room = player.room
        local d = player.mini_game_data.data
        if d.friend_id ~= 0 then
            local friend = room:getPlayerById(d.friend_id)
            friend:doNotify("UpdateMiniGame", data)
        end
    end,
}


local m_1v2_getLogic = function()
    local ty_1v2_logic = GameLogic:subclass("ty_1v2_logic")

    function ty_1v2_logic:initialize(room)
        GameLogic.initialize(self, room)
        self.role_table = { nil, nil, { "lord", "rebel", "rebel" } }
    end

    function ty_1v2_logic:assignRoles()
        local room = self.room
        local n = #room.players
        for i = 1, n do
            local p = room.players[i]
            p.role = "hidden"
            room:setPlayerProperty(p, "role_shown", true)
            room:broadcastProperty(p, "role")
        end
        local x = math.random(1, 3)
        room.players[1].role = "lord"
    end

    function ty_1v2_logic:chooseGenerals()
        local room = self.room ---@type Room
        local generalNum = 6
        local n = room.settings.enableDeputy and 2 or 1
        local chengzhuskill = { "ty_1v2_cc&", "ty_1v2_fc&", "ty_1v2_hf&", "ty_1v2_hl&", "ty_1v2_jl&", "ty_1v2_jm&",
            "ty_1v2_jz&", "ty_1v2_ly&", "ty_1v2_wc&", "ty_1v2_xy&", "ty_1v2_xz&", "ty_1v2_yc&", "ty_1v2_ya&",
            "ty_1v2_xc&", "ty_1v2_sc&" }
        local skill = table.random(chengzhuskill, 1)[1]
        for i = 1, 3, 1 do
            room:doBroadcastNotify("ShowToast",
                "<font color='red'>本局城池为：" .. Fk:translate(skill) .. "，点击左上角查看城主技能，若不熟悉模式，请前往玩法一览→模式简介查看模式规则!</font>")
        end
        room:setBanner("@[:]skillchengchi", skill)
        local lord = room:getLord()
        for _, g in pairs(Fk.generals) do
            if not table.contains(witheextensionName, g.package.extensionName) then
                table.removeOne(room.general_pile, g.name)
            end
        end
        room:setCurrent(lord)
        local players = room.players
        table.shuffle(players)
        local generals = room:getNGenerals(#players * generalNum + 2)
        --有ai就，没有叫地主环境了
        local who_lord = players[1] --默认第一个是地主
        local maxpoint = 1
        local isOver = false


        local req = Request:new(players, "AskForGeneral")
        req.timeout = self.room:getSettings('generalTimeout')
        for i, p in ipairs(players) do
            local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
            req:setData(p, { arg, 0, false, false })
            req:setDefaultReply(p, table.random(arg, n))
        end

        for _, p in ipairs(players) do
            req:getResult(p)
        end

        for _, player in ipairs(players) do
            local choice = room:askToChoice(player, {
                choices = { "是", "否" },
                prompt = "是否要成为地主？",
                cancelable = false,
            })
            if choice == "是" then
                isOver = true
                who_lord = player
                break
            end
        end
        if isOver == false then
            who_lord = table.random(players)
        end
        for i, p in ipairs(players) do
            if p.id == who_lord.id then
                p.role = "lord"
                room:setPlayerMark(p, "chengzhu", skill)
            else
                p.role = "rebel"
            end
        end
        for _, p in ipairs(players) do
            room:setPlayerProperty(p, "role_shown", true)
            room:broadcastProperty(p, "role")
        end

        --这时候正式开始选将，农民互通
        local lordlist = {}
        local farmerlist = {}
        local lord_general = {}
        local farmer_general = {}
        for i, p in ipairs(players) do
            local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
            if p.role == "lord" then
                local count = #generals
                table.insert(arg, generals[count])
                table.insert(arg, generals[count - 1])
                table.insert(lordlist, p)
                table.insert(lord_general, arg)
            else
                table.insert(farmerlist, p)
                table.insert(farmer_general, arg)
            end
        end
        local req2 = room:askToMiniGame(players, {
            skill_name = "AskForGeneral",
            game_type = "ty_1v2_sel",
            data_table = {
                [lordlist[1].id] = { --地主没有队友
                    friend_id = 0,
                    me = lord_general[1],
                    friend = {},
                    num = n,
                },
                [farmerlist[1].id] = {
                    friend_id = farmerlist[2].id,
                    me = farmer_general[1],
                    friend = farmer_general[2],
                    num = n,
                },
                [farmerlist[2].id] = {
                    friend_id = farmerlist[1].id,
                    me = farmer_general[2],
                    friend = farmer_general[1],
                    num = n,
                },
            }
        })
        for _, p in ipairs(players) do
            local general = req2:getResult(p)
            room:setPlayerGeneral(p, general[1], true, true)
            room:setDeputyGeneral(p, general[2])
            room:findGeneral(general)
        end

        room:askToChooseKingdom(players)
        --农民通牌
        farmerlist[1]:addBuddy(farmerlist[2])
        farmerlist[2]:addBuddy(farmerlist[1])
        for _, p in ipairs(players) do
            room:broadcastProperty(p, "general")
            room:broadcastProperty(p, "deputyGeneral")
        end
        --设置倍率

        --这时候再调一下位置
        local player_circle = {}
        local players = room.players
        local p = 1

        for i = 1, #players do
            if players[i].role == "lord" then
                p = i
                break
            end
        end
        for j = p, #players do
            table.insert(player_circle, players[j])
        end
        for j = 1, p - 1 do
            table.insert(player_circle, players[j])
        end

        room:arrangeSeats(player_circle)
    end

    function ty_1v2_logic:attachSkillToPlayers()
        local room = self.room

        local addRoleModSkills = function(player, skillName)
            local skill = Fk.skills[skillName]
            if not skill then
                fk.qCritical("Skill: " .. skillName .. " doesn't exist!")
                return
            end
            if skill:hasTag(Skill.Lord) then
                return
            end
            if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
                return
            end
            room:handleAddLoseSkills(player, skillName, nil, false)
        end
        for _, p in ipairs(room.alive_players) do
            for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
                addRoleModSkills(p, s)
            end
            if p.role == "lord" then
                local skill = p:getMark("chengzhu")
                room:handleAddLoseSkills(p, skill, nil, false)
                if p:getMark("chengzhu") == "ty_1v2_hl&" then
                    room:handleAddLoseSkills(p, "mashu|wushuang")
                end
            else
                room:setPlayerMark(p, "@ty_1v2_shaxue", 3)
            end
        end
    end

    return ty_1v2_logic
end

local ty_1v2_mode = fk.CreateGameMode {
    name = "ty_1v2_mode",
    minPlayer = 3,
    maxPlayer = 3,
    rule = "ty_1v2_gamerule&",
    main_mode = "1v2_mode",
    logic = m_1v2_getLogic,
    surrender_func = function(self, playedTime)
        local surrenderJudge = { { text = "time limitation: 0.5 min", passed = playedTime >= 20 } }
        if Self.role ~= "lord" then
            local tps = ""
            if #table.filter(Fk:currentRoom().alive_players, function(p)
                    return p.role == "rebel"
                end) == 1 then
                tps = "1v2: da bu guo"
            else
                tps = "1v2: ni tou ge ji mao"
            end
            table.insert(surrenderJudge, {
                text = tps,
                passed = #table.filter(Fk:currentRoom().alive_players, function(p)
                    return p.role == "rebel"
                end) == 1
            })
        elseif Self.role == "lord" and Self:hasSkill("ty_1v2_jm&") then
            local ips = ""
            if #table.filter(Fk:currentRoom().alive_players, function(p)
                    return p.role == "loyalist"
                end) == 0 then
                ips = "1v2: gai tou le"
            else
                ips = "1v2: ni tou ge pi"
            end
            table.insert(surrenderJudge, {
                text = ips,
                passed = #table.filter(Fk:currentRoom().alive_players, function(p)
                    return p.role == "loyalist"
                end) == 0
            })
        end

        return surrenderJudge
    end,
    get_adjusted = function(self, player)
        if player.role == "lord" then
            return { hp = player.hp + 1, maxHp = player.maxHp + 1 }
        end
        return {}
    end,
    reward_punish = function(self, victim, killer)
        local room = victim.room
        if victim.role == "rebel" then
            for _, p in ipairs(room:getOtherPlayers(victim)) do
                if p.role == "rebel" then
                    local choices = { "draw2", "Cancel" }
                    if p:isWounded() then
                        table.insert(choices, 2, "recover")
                    end
                    local choice = room:askToChoice(p, {
                        choices = choices,
                        skill_name = "PickLegacy",
                    })
                    if choice == "draw2" then
                        p:drawCards(2, "game_rule")
                    else
                        room:recover {
                            who = p,
                            num = 1,
                            recoverBy = p,
                            skillName = "game_rule",
                        }
                    end
                end
            end
        end
    end,
    build_draw_pile = function(self)
        local draw, void = GameMode.buildDrawPile(self)
        local blacklist = { "supply_shortage", "indulgence" }
        local whitelist = { "substituting" }

        for i = #void, 1, -1 do
            local id = void[i]
            local card = Fk:getCardById(id)
            local name = card.name
            if table.contains(whitelist, name) then
                table.remove(void, i)
                table.insert(draw, id)
            end
        end

        for i = #draw, 1, -1 do
            local id = draw[i]
            local card = Fk:getCardById(id)
            local name = card.name
            if table.contains(blacklist, name) then
                table.remove(draw, i)
                table.insert(void, id)
            end
        end

        return draw, void
    end
}

Fk:loadTranslationTable {
    ["ty_1v2_mode"] = "兵临城下",
    ["MahjongSoul_ty_1v2"] = "兵临城下",
    [":ty_1v2_mode"] = ty_desc_1v2,
    ["@[:]skillchengchi"] = "本局城池",
    ["@ty_1v2_shaxue"] = "歃血",

    ["ty_1v2_choslord"] = "选择地主",
    ["#ty_1v2_mode_findai"] = "本局有AI，不进行抢地主",
    ["#ty_1v2_less"] = "你破产啦！",

    ["PickLegacy"] = "挑选遗产",

    ["time limitation: 0.5 min"] = "游戏时长达到20秒",
    ["1v2: ni tou ge ji mao"] = "你投个戟吧，兄弟还没投呢",
    ["1v2: ni tou ge pi"] = "你兄弟还活着，你投个集贸啊",
    ["1v2: gai tou le"] = "兄弟噶了，我还活个集贸，点了",
    ["1v2: da bu guo"] = "打又打不过，跑又跑不了，点了",
}
extension:addGameMode(ty_1v2_mode)
return extension
